import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_template/widget/toast.dart';

///文件路径工具类
class PathUtils {
  PathUtils._internal();

  ///获取缓存目录路径
  static Future<String> getCacheDirPath() async {
    Directory directory = await getTemporaryDirectory();
    return directory.path;
  }

  ///获取文件缓存目录路径
  static Future<String> getFilesDirPath() async {
    Directory directory = await getApplicationSupportDirectory();
    return directory.path;
  }

  ///获取文档存储目录路径
  static Future<String> getDocumentsDirPath() async {
    Directory directory = await getApplicationDocumentsDirectory();
    return directory.path;
  }
  
 ///加载缓存
  static Future<String> loadCache() async {
    try {
      Directory tempDir = await getTemporaryDirectory();
      double value = await _getTotalSizeOfFilesInDir(tempDir);
      return _renderSize(value);
    } catch (err) {
	  return "0.00B";
    }
  }
///格式化文件大小
  static _renderSize(double value) {
    if (null == value) {
      return 0;
    }
    List<String> unitArr = List()
      ..add('B')
      ..add('K')
      ..add('M')
      ..add('G');
    int index = 0;
    while (value > 1024) {
      index++;
      value = value / 1024;
    }
    String size = value.toStringAsFixed(2);
    return size + unitArr[index];
  }
  
  /// 递归方式 计算文件的大小
  static Future<double> _getTotalSizeOfFilesInDir(final FileSystemEntity file) async {
    try {
      if (file is File) {
            int length = await file.length();
            return double.parse(length.toString());
          }
      if (file is Directory) {
            final List<FileSystemEntity> children = file.listSync();
            double total = 0;
            if (children != null)
              for (final FileSystemEntity child in children)
                total += await _getTotalSizeOfFilesInDir(child);
            return total;
          }
      return 0;
    } catch (e) {
      print(e);
      return 0;
    }
  }
  
  static void clearCache() async {
    //此处展示加载loading
    try {
      Directory tempDir = await getTemporaryDirectory();
      //删除缓存目录
	  print("清除完成");
      await delDir(tempDir);
      await loadCache();
      //ToastUtils.toast(msg: '清除缓存成功');
    } catch (e) {
	  print("清除失败");
      print(e);
      //ToastUtils.toast(msg: '清除缓存失败');
    } finally {
      //此处隐藏加载loading
	  print("正在清除");
    }
  }
  ///递归方式删除目录
  static Future<Null> delDir(FileSystemEntity file) async {
    try {
      if (file is Directory) {
            final List<FileSystemEntity> children = file.listSync();
            for (final FileSystemEntity child in children) {
              await delDir(child);
            }
          }
      await file.delete();
    } catch (e) {
      print(e);
    }
  }
}
